package com.heima.user.service.impl;

import apis.wemedia.IWemediaClient;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.BehaviorConstans;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.Behavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.FollowDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.service.ApUserFanService;
import com.heima.user.service.ApUserFollowService;
import com.heima.user.service.ApUserService;
import com.heima.utils.thread.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {
    @Autowired
    private ApUserFanService apUserFanService;

    @Autowired
    private ApUserService apUserService;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private IWemediaClient wemediaClient;

    /**
     * 用户关注行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(FollowDto dto) {
        if (dto == null || ThreadLocalUtil.get() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userId = ThreadLocalUtil.get();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (dto.getOperation() == 0) {
                    Concern(dto,userId);
                } else if (dto.getOperation() == 1) {
                    Unfollow(dto,userId);
                }
            }
        }).start();
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消关注
     * @param dto
     * @param userId
     */
    private void Unfollow(FollowDto dto, Integer userId) {
        //删除用户的关注表
        remove(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId).eq(ApUserFollow::getFollowId, dto.getAuthorId()));
        //删除作者的粉丝表
        apUserFanService.remove(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, dto.getAuthorId()).eq(ApUserFan::getFanId, userId));

        cacheService.zRemove(userId + "_" + dto.getArticleId() + "_follow", dto.getAuthorId().toString());
    }

    /**
     * 用户关注
     * @param dto
     * @param userId
     */
    private void Concern(FollowDto dto, Integer userId) {
        ResponseResult res = wemediaClient.getWmUserById(dto.getAuthorId());
        WmUser wmUser = JSON.parseObject(JSON.toJSONString(res.getData()), WmUser.class);
        ApUserFollow apUserFollow = new ApUserFollow();
        ApUser apUser = apUserService.getById(wmUser.getApUserId());
        apUserFollow.setFollowId(apUser.getId());
        apUserFollow.setFollowName(apUser.getName());
        apUserFollow.setUserId(userId);
        save(apUserFollow);

        ApUserFan apUserFan = new ApUserFan();
        ApUser apUserNow = apUserService.getById(userId);
        apUserFan.setUserId(apUser.getId());
        apUserFan.setFanId(userId);
        apUserFan.setFanName(apUserNow.getName());
        apUserFanService.save(apUserFan);
//        List filed = (List) cacheService.hGet(userId + "_" + dto.getArticleId() + BehaviorConstans.CACHE_END, "filed");
//        filed.add("demo");
//         cacheService.hPut(userId + "_" + dto.getArticleId() + BehaviorConstans.CACHE_END, "filed",filed.toString());
        cacheService.zAdd(userId + "_" + dto.getArticleId() + "_follow", dto.getAuthorId().toString(), System.currentTimeMillis());
    }
}
